"""
法大大相关流程
"""
import base64
import json
import uuid
from django.db import transaction

from .api import FddApi
from src.utils import record
from common.models import TbMiniappUser, TbCourseTask, FddContract, FddUser


class FddDirector:
    def __init__(self):
        self.fur = record.FddUserRecord()
        self.ftr = record.FddTemplateRecord()
        self.fcr = record.FddContractRecord()

    def register(self, **kwargs):
        """
        给用户注册法大大账号
        """
        # 取参
        # --- start ---
        open_id = kwargs.get("open_id")
        account_type = kwargs.get("account_type")
        # --- end ---
        result = FddApi().register(open_id=open_id, account_type=account_type)
        customer_id = result.get("data")
        fdd_user = {
            "open_id": open_id,
            "account_type": account_type,
            "customer_id": customer_id
        }
        fdd_user = self.fur.create_record(**fdd_user)
        return self.fur.record_obj_serializer(fdd_user)

    def get_person_verify_url(self, **kwargs):
        """
        获取个人实名认证地址
        """
        customer_id = kwargs.get("customer_id")
        customer_name = kwargs.get("customer_name")
        customer_ident_no = kwargs.get("customer_ident_no")
        mobile = kwargs.get("mobile")
        area_code = kwargs.get("area_code")
        ident_front_path = kwargs.get("ident_front_path")
        ident_back_path = kwargs.get("ident_back_path")
        return_url_params = kwargs.get("return_url_params")
        person_verify = {
            "customer_id": customer_id,
            "customer_name": customer_name,
            "customer_ident_no": customer_ident_no,
            "mobile": mobile,
            "area_code": area_code,
            "ident_front_path": ident_front_path,
            "ident_back_path": ident_back_path,
            "return_url_params": return_url_params,
        }
        result = FddApi().get_person_verify_url(**person_verify)
        result_data = result.get("data")
        transactionNo = result_data.get("transactionNo")
        url = result_data.get("url")
        url = base64.b64decode(url)
        result = {
            "transactionNo": transactionNo,
            "url": url.decode()
        }
        return result

    def get_company_verify_url(self, **kwargs):
        """
        获取企业认证页面
        """
        # 取参
        # --- start ---
        customer_id = kwargs.get("customer_id")  # 必传
        # CompanyInfo 企业信息
        company_name = kwargs.get("company_name")  # 企业名称
        credit_no = kwargs.get("credit_no")  # 统一社会信用代码
        credit_image_path = kwargs.get("credit_image_path")  # 统一社会信用代码证件照路径
        # LegalInfo 法人信息
        legal_name = kwargs.get("legal_name")  # 法人姓名
        legal_id_front_path = kwargs.get("legal_id_front_path")
        legal_id_back_path = kwargs.get("legal_id_back_path")
        # --- end ---
        person_verify = {
            "customer_id": customer_id,
            "company_name": company_name,
            "credit_no": credit_no,
            "credit_image_path": credit_image_path,
            "legal_name": legal_name,
            "legal_id_front_path": legal_id_front_path,
            "legal_id_back_path": legal_id_back_path,
        }
        result = FddApi().get_company_verify_url(**person_verify)
        print(result)
        result_data = result.get("data")
        transactionNo = result_data.get("transactionNo")
        url = result_data.get("url")
        url = base64.b64decode(url)
        result = {
            "transactionNo": transactionNo,
            "url": url.decode()
        }
        return result

    def uploadtemplate(self, **kwargs):
        """
        上传模板
        """
        template_name = kwargs.get("template_name")
        doc_url = kwargs.get("doc_url")
        with transaction.atomic():
            template_info = {
                "template_name": template_name,
                "doc_url": doc_url,
                "template_id": uuid.uuid1().hex[0:10]
            }
            result = FddApi().uploadtemplate(**template_info)
            # 入库模板
            self.ftr.create_record(**template_info)
            return result

    def contractFiling(self, **kwargs):
        """
        合同归档
        """
        contract_id = kwargs.get("contract_id")
        result = FddApi().contractFiling(contract_id=contract_id)
        return result

    def generate_contract(self, **kwargs):
        """
        填充模板
        """
        # 模板信息
        doc_title = kwargs.get("doc_title")
        template_id = kwargs.get("template_id")
        course_task_id = kwargs.get("course_task_id")
        # 甲方
        compony_name = kwargs.get("compony_name")
        compony_address = kwargs.get("compony_address")
        # 法定代表人
        legal_name = kwargs.get("legal_name")
        agent_name = kwargs.get("agent_name")
        agent_phone = kwargs.get("agent_phone")
        # 乙方
        teacher_name = kwargs.get("teacher_name")
        teacher_gender = kwargs.get("teacher_gender")
        teacher_idcard = kwargs.get("teacher_idcard")
        teacher_address = kwargs.get("teacher_address")
        teacher_phone = kwargs.get("teacher_phone")
        # 合同期限
        start_year = kwargs.get("start_year")
        start_month = kwargs.get("start_month")
        start_day = kwargs.get("start_day")
        end_year = kwargs.get("end_year")
        end_month = kwargs.get("end_month")
        end_day = kwargs.get("end_day")
        Probation_period = kwargs.get("Probation_period")
        # 劳动合同补充
        remark_1 = kwargs.get("remark_1")
        remark_2 = kwargs.get("remark_2")
        remark_3 = kwargs.get("remark_3")
        # 签约日期
        company_sign_year = kwargs.get("company_sign_year")
        company_sign_month = kwargs.get("company_sign_month")
        company_sign_day = kwargs.get("company_sign_day")
        teacher_sign_year = kwargs.get("teacher_sign_year")
        teacher_sign_month = kwargs.get("teacher_sign_month")
        teacher_sign_day = kwargs.get("teacher_sign_day")
        # 组合参数
        parameter_map = {
            "compony_name": compony_name,
            "compony_address": compony_address,
            "legal_name": legal_name,
            "agent_name": agent_name,
            "agent_phone": agent_phone,
            "teacher_name": teacher_name,
            "teacher_gender": teacher_gender,
            "teacher_idcard": teacher_idcard,
            "teacher_address": teacher_address,
            "teacher_phone": teacher_phone,
            "start_year": start_year,
            "start_month": start_month,
            "start_day": start_day,
            "end_year": end_year,
            "end_month": end_month,
            "end_day": end_day,
            "Probation_period": Probation_period,
            "remark_1": remark_1,
            "remark_2": remark_2,
            "remark_3": remark_3,
            "company_sign_year": company_sign_year,
            "company_sign_month": company_sign_month,
            "company_sign_day": company_sign_day,
            "teacher_sign_year": teacher_sign_year,
            "teacher_sign_month": teacher_sign_month,
            "teacher_sign_day": teacher_sign_day,
        }
        parameter_map = json.dumps(parameter_map)
        contract_id = uuid.uuid1().hex[0:10]
        generate_info = {
            "doc_title": doc_title,
            "template_id": template_id,
            "contract_id": contract_id,
            "parameter_map": parameter_map,
        }
        result = FddApi().generate_contract(**generate_info)
        result_code = result.get("code")
        if result_code == "1000":
            with transaction.atomic():
                contract_info = {
                    "contract_id": contract_id,
                    "template_id": template_id,
                    "doc_title": doc_title,
                    "doc_url": result.get("download_url"),
                    "view_url": result.get("viewpdf_url"),
                    "course_task_id": course_task_id
                }
                self.fcr.create_record(**contract_info)
                return contract_info
        return result

    def uploaddocs(self, **kwargs):
        """
        上传合同
        """
        contract_id = kwargs.get("contract_id")
        doc_title = kwargs.get("doc_title")
        doc_url = kwargs.get("doc_url")
        contract_info = {
            "contract_id": contract_id,
            "doc_title": doc_title,
            "doc_url": doc_url,
        }
        result = FddApi().uploaddocs(**contract_info)
        return result

    def viewContract(self, **kwargs):
        """
        查看合同
        """
        contract_id = kwargs.get("contract_id")
        result = FddApi().viewContract(contract_id=contract_id)
        return result

    def extsign(self, **kwargs):
        """
        手动签署
        """
        course_task_id = kwargs.get("course_task_id")
        user: TbMiniappUser = kwargs.get("user")
        contract: FddContract = self.fcr.filter_record_obj(course_task_id=course_task_id).first()
        contract_id = contract.contract_id
        if user.role == 10:
            fdd_user_id = user.teacher_id
        else:
            fdd_user_id = user.organization_id
        fdd_user: FddUser = self.fur.filter_record_obj(open_id=fdd_user_id).first()
        customer_id = fdd_user.customer_id
        doc_title = contract.doc_title
        sign_info = {
            "contract_id": contract_id,
            "customer_id": customer_id,
            "doc_title": doc_title,
            "transaction_id": uuid.uuid1().hex[0:10],
        }
        result = FddApi().extsign(**sign_info)
        result = {
            "url": result.url
        }
        return result

    def get_contract_info(self, **kwargs):
        """
        获取合同信息
        """
        course_task_id = kwargs.get("course_task_id")
        contract = self.fcr.filter_record_obj(course_task_id=course_task_id).first()
        return self.fcr.record_obj_serializer(contract)


class FddTest:
    def get_person_verify_url(self):
        """
        获取个人实名认证地址
        """
        # params = {
        #     "customer_id": "22EC1E1CE7E80C1A465B26C5AE83A79E",
        # }
        params = {
            'customer_id': '22EC1E1CE7E80C1A465B26C5AE83A79E',
            'customer_name': '1',
            'customer_ident_no': '2',
            'ident_front_path': 'https://jsy.unicorn-go.com/static/media/fbbbe9c20f5511efaa700da4d3710d1a.jpg',
            'ident_back_path': 'https://jsy.unicorn-go.com/static/media/fa0de8280f5511efaa700da4d3710d1a.jpg'
        }
        result = FddDirector().get_person_verify_url(**params)
        print(result)

    def upload_template(self):
        """
        上传模板
        """
        params = {
            "doc_url": "https://jsy.unicorn-go.com/static/media/7f0781280ee911efaa700da4d3710d1a.pdf",
            "template_name": "聚师云合作协议",
        }
        result = FddDirector().uploadtemplate(**params)
        print(result)

    def generate_contract(self):
        """
        填充模板
        """
        params = {
            "doc_title": "测试合同",
            "template_id": "a41633a20e",
            "compony_name": "测试",
            "teacher_name": "测试老师",
            "compony_address": "测试地址",
            "teacher_gender": "男",
            "company_sign_year": "2014",
            "company_sign_month": "11",
            "company_sign_day": "22",
        }
        result = FddDirector().generate_contract(**params)
        print(result)

    def uploaddocs(self):
        """
        上传合同
        """
        params = {
            "contract_id": "d817ff0a0f",
            "doc_title": "测试合同",
            "doc_url": "https://testapi.fadada.com/api/downLoadContract.action?app_id=406595&v=2.0&timestamp=20240511214618&contract_id=d817ff0a0f&msg_digest=NDUxODAwN0I4NzZDQzI3RjFDQjgyMzVBNkE3QUEyNUNCNURFNzQxNw==",
        }
        result = FddDirector().uploaddocs(**params)
        print(result)

    def viewContract(self):
        """
        查看合同
        """
        params = {
            "contract_id": "892ceaa60e",
        }
        result = FddDirector().viewContract(**params)
        print(result)
        return result

    def extsign(self):
        """
        手动签署
        """
        user = TbMiniappUser.objects.get(uid="798caa580f5111efaa700da4d3710d1a")
        params = {
            "contract_id": "892ceaa60e",
            "user": user
            # "customer_id": "FDA2A7285623E54E4D07FA5F640F14B6",
            # "doc_title": "测试",
        }
        result = FddDirector().extsign(**params)
        print(result)
        return result

    def contractFiling(self):
        """
        合同归档
        """
        params = {
            "contract_id": "892ceaa60e"
        }
        result = FddDirector().contractFiling(**params)
        print(result)
        return result

    def get_company_verify_url(self):
        """
        获取企业认证页面
        """
        params = {
            "customer_id": "1DAF22B1F74CACA6F4021F6DDE155A32",
            "company_name": "上岸甄选",
            "credit_no": "111111",
            "credit_image_path": "https://jsy.unicorn-go.com/static/media/ececf7f40f7011efaa700da4d3710d1a.jpg",
            "legal_name": "王",
            "legal_id_front_path": "https://jsy.unicorn-go.com/static/media/1e3b45540f7111efaa700da4d3710d1a.jpg",
            "legal_id_back_path": "https://jsy.unicorn-go.com/static/media/b56ee6880f7111efaa700da4d3710d1a.jpg",
        }
        result = FddDirector().get_company_verify_url(**params)
        print(result)
        return result


def test():
    # FddTest().upload_template()  # 上传合同模板
    # FddTest().generate_contract()  # 填充模板
    FddTest().uploaddocs()  # 上传合同
    # return FddTest().viewContract()  # 查看合同
    # return FddTest().extsign()  # 签署合同
    # FddTest().get_person_verify_url()  # 获取个人实名认证地址
    # FddTest().get_company_verify_url()  # 获取企业认证页面
    # FddTest().get_person_verify_url()  # 获取个人实名认证地址
    # return FddTest().contractFiling()
